package pl.vanta.utils.xml.xbeans;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * @author Krzysztof Wolny (k.wolny@wasko.pl)
 */

class XBeanConverterImplXmlEncoder implements XBeanConverter
{
	@Override
	public Object toBean(String xml)
	{
		try
		{
			ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes("UTF-8"));

			XMLDecoder decoder = new XMLDecoder(bais);

			return decoder.readObject();
		}
		catch (Exception exc)
		{
			exc.printStackTrace();

			return null;
		}
	}

	@Override
	public String toXml(Object object)
	{
		try
		{
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			XMLEncoder encoder = new XMLEncoder(baos);
			encoder.writeObject(object);

			encoder.close();

			return baos.toString("UTF-8");
		}
		catch (Exception e)
		{
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T toBean(String xml, Class<T> clazz)
	{
		Object o = toBean(xml);

		if (clazz.isInstance(o))
		{
			return (T) o;
		}
		else
		{
			return null;
		}
	}
}
